package com.sz.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sz.dao.CheckGroupDao;
import com.sz.entity.PageResult;
import com.sz.entity.QueryPageBean;
import com.sz.pojo.CheckGroup;
import com.sz.pojo.CheckItem;
import com.sz.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public void add(CheckGroup checkGroup, List<Integer> checkitemIds) {
        checkGroupDao.add(checkGroup);
        Integer checkGroupId = checkGroup.getId();
       if (null != checkitemIds){
           for (Integer checkitemId : checkitemIds) {
               checkGroupDao.addCheckGroupCheckItem(checkGroupId,checkitemId);
           }
       }
    }

    @Override
    public PageResult<CheckGroup> findPage(QueryPageBean queryPageBean) {
        //使用pageHelper分页参数设置
        Page<CheckGroup> startPage = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //判断是否有查询条件
        if (!StringUtils.isEmpty(queryPageBean.getQueryString())) {
            //有则拼接%，实现模糊查询
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        //查询条件
        Page<CheckGroup> page= checkGroupDao.findByCondition(queryPageBean.getQueryString());
        //封装到pageResult中
        PageResult<CheckGroup> pageResult = new PageResult<>(page.getTotal(),page.getResult());
        //返回
        return pageResult;
    }

    @Override
    public CheckGroup findById(int id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(int id) {
        return checkGroupDao.findCheckItemIdsByCheckGroupId(id);
    }

    @Override
    @Transactional
    public void update(CheckGroup checkGroup, List<Integer> checkitemIds) {
        //更新检查组
        checkGroupDao.update(checkGroup);
        //获取检查组id
        Integer checkGroupId = checkGroup.getId();
        //通过检查组id删除与检查项旧关系
        checkGroupDao.removeCheckGroupCheckItem(checkGroupId);
        //非空判断
        if(!CollectionUtils.isEmpty(checkitemIds)) {
            for (Integer checkitemId : checkitemIds) {
                //添加 新关系
                checkGroupDao.addCheckGroupCheckItem(checkGroupId,checkitemId);

            }
        }
        //事务控制
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }
}
